package com.wk.search.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.*;
import com.wk.search.model.SearchEntity;
import com.wk.search.service.SearchHouseService;
import com.wk.search.utils.HttpUtils;
import com.wk.search.utils.MailSenderUtil;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Log4j
@Service
public class SearchHouseServiceImpl implements SearchHouseService {
    @Resource
    private MailSenderUtil mailSenderUtil;

    @Value("${spring.search.searchUrls}")
    private String searchUrls;


    @Override
    public void search() throws IOException {
        SearchEntity entity = new SearchEntity();
        entity.setScope(5F);
        entity.setKeywordsList("开车,百利,丸味,湿巾,猫草片,绿十字");
        entity.setBlackWordsList("团购");
        List<String> receive = new ArrayList<String>();
        receive.add("1139406816@qq.com");
        entity.setReceiverList(receive);
        send(entity);
    }


    private String[] getLines(String searchUrl, String keyword) throws Exception {
        // 配置Header
        String url = searchUrl + keyword;
        HttpUtils httpUtils = new HttpUtils();
        String result = httpUtils.doGetHtml(url);
        //获取网页源码
        return result.split("\\r?\\n");
    }

    private void send(SearchEntity searchInfo) throws IOException {
        Float scope = searchInfo.getScope();
        List<String> receivers = searchInfo.getReceiverList();
        String[] keywords = searchInfo.getKeywordsList().split(",");
        StringBuilder validText = new StringBuilder();
        StringBuilder infoStr = new StringBuilder();
        String[] urlList = searchUrls.split(",");
        int year = Calendar.getInstance().get(Calendar.YEAR);
        try {
            for (String keyword : keywords) {
                for (String searchUrl : urlList) {
                    String[] lines = getLines(searchUrl, keyword);
                    //逐行读取网页源码
                    for (String line : lines) {
                        //找到有效数据
                        if (line.contains("group_topic_by_time") || (line.contains("\n") && line.endsWith("</a></td>"))) {
                            validText = new StringBuilder(line);
                        }
                        if (line.contains("td-time") && (line.contains(year + "") || line.contains(year - 1 + ""))) {
                            validText.append(line);
                            int startIndex = validText.indexOf(year + "-");
                            String dateStr = validText.substring(startIndex, validText.indexOf("\" nowrap="));
                            String urlStr = validText.substring(validText.indexOf("http"), validText.indexOf("\" onclick"));
                            String titleStr = validText.substring(validText.indexOf("title=\"") + 7, validText.lastIndexOf("<td class=\"td-time\""));
                            if (titleStr.contains("</a></td>")) {
                                titleStr = titleStr.substring(0, titleStr.indexOf("</a></td>"));
                            }
                            if (titleStr.contains("\">")) {
                                titleStr = titleStr.substring(0, titleStr.indexOf("\">"));
                            }
                            String info = "[" + keyword + "]\r\n" + "标题：" + titleStr + "\r\n" + dateStr + "\r\n" + urlStr + "\r\n";
                            LocalDateTime start;
                            try {
                                start = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                            }catch (Exception e){
                                continue;
                            }
                            LocalDateTime end = LocalDateTime.now();
                            Duration duration = Duration.between(start, end);
                            long minutes = duration.toMinutes();
                            if (minutes < scope){
                                infoStr.append(info).append("\r\n");
                            }
                        }
                    }
                }
            }
            if (infoStr.length() > 0) {
                String str = "====================================" + "\r\n" + "检索范围: " + scope + "分钟内" + "\r\n" + "关键词: " + Arrays.toString(keywords) + "\r\n" + "====================================" + "\r\n";
                for (String receiver : receivers) {
                    mailSenderUtil.sendSimpleMail(receiver, "猫组开车小助手", str + infoStr.toString());
                }
                System.out.println("邮件发送成功");
            } else {
                System.out.println("未找到合适信息");
            }
        } catch (Exception e) {
            System.out.println("邮件发送失败");
            e.printStackTrace();
        }
    }
}
